package com.zian.utils;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;

import com.zian.exception.BizIllegalException;
import com.zian.properties.AliProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Component
@Import(AliProperties.class)
public class AliOssUtil {


    @Autowired
    private AliProperties properties;

    /**
     * 文件上传
     *
     * @param bytes
     * @param objectName
     * @return
     */
    public String upload(byte[] bytes, String objectName) {

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(properties.getEndpoint(), properties.getAccessKeyId(), properties.getAccessKeySecret());

        try {
            // 创建PutObject请求。
            ossClient.putObject(properties.getBucketName(), objectName, new ByteArrayInputStream(bytes));
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        //文件访问路径规则 https://BucketName.Endpoint/ObjectName
        StringBuilder stringBuilder = new StringBuilder("https://");
        stringBuilder
                .append(properties.getBucketName())
                .append(".")
                .append(properties.getEndpoint())
                .append("/")
                .append(objectName);

        log.info("文件上传到:{}", stringBuilder.toString());

        return stringBuilder.toString();
    }

    /**
     * 多文件上传
     *
     * @param files 文件数组
     * @return 文件访问路径集合
     */
    public List<String> uploadArrayFile(MultipartFile[] files) {
        // 创建OSSClient实例。
        List<String> list = new ArrayList<>();
        try {
            //设置文件名
            for (MultipartFile file : files) {
                String upload = upload(file.getBytes(), generateFileName(file));
                list.add(upload);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return list;
    }

    /**
     * 生成文件名
     *
     * @param file
     * @return
     */
    public String generateFileName(MultipartFile file) {
        log.info("开始上传文件");
        if (file == null) throw new BizIllegalException("文件不能为空");
        String name = file.getOriginalFilename();
        if (StrUtil.isBlank(name)) throw new BizIllegalException("请选择文件后上传");

        String[] split = name.split("\\.");
        // uuid + 文件的后缀名来保证文件不会重复
        return UUID.randomUUID() + "." + split[split.length - 1];
    }


}
